package com.dp.service.hdnewsmanage;

import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

import javax.persistence.Query;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.dp.pojo.JsonPage;
import com.dp.pojo.NewsVo;
import com.dp.pub.SysProperty;
import com.dp.service.impl3.BaseImpl;
import com.dp.util.BookConfig;
import com.dp.util.DataMap;
import com.dp.util.GenerateNewsHtml;
import com.dp.util.ImageScalee;
import com.dp.vo.NewsContenttitle;
import com.dp.vo.NewsResources;
import com.dp.vo.TAreainfo;
import com.dp.vo.TYpContents;

@Service
@Transactional
public class YpnewsServiceImpl extends BaseImpl {
	
	private static int YPNEWS_TYPE = 3;
	
	/**
	 * 获得黄页信息总记录数
	 * @param hashMap
	 * @return Integer
	 */
	public Integer findAllYpNewsEntityCount(DataMap hashMap){
		NewsVo news=(NewsVo) hashMap.get("news");
		Object s_role_id = hashMap.get("role_id");
		Object s_user_id = hashMap.get("user_id");
		String userids = (String)hashMap.get("userids");
		Integer iCount = 0; 
		try {
			//this.init();
			StringBuffer sqlS =new StringBuffer("select count(nc.cid) from t_ypcontents tc,news_contenttitle nc ");
			if(news!=null && news.getChannelId()!=null&& news.getChannelId().toString().trim().length() > 0) {
				sqlS.append(",news_extends_channel nec,news_extends_channel_title nect ");
				sqlS.append(" where nec.channel_id='"+news.getChannelId()+"' and nec.channleid=nect.channleid and nc.cid=nect.cid ");
				sqlS.append(" and nc.contentid=tc.contentid");
			}
			else
				sqlS.append(" where nc.contentid=tc.contentid ");
			if(s_role_id!=null&&!"".equals(s_role_id)) {
				sqlS.append(" and tc.user_id = '"+ s_user_id +"'");
			}else if(userids!=null){
				sqlS.append(" and tc.user_id in ("+ userids +")");
			}
			
			if(news!=null){
				if(news.getContentName()!=null&& news.getContentName().toString().trim().length() > 0){
					sqlS.append(" AND tc.contenttitle like '%"+news.getContentName().toString().trim() + "%'");
				}
				if(news.getContentStatus()!=null&& news.getContentStatus().toString().trim().length() > 0){
					sqlS.append(" AND tc.content_status='"+news.getContentStatus().toString().trim() + "'");
				}
				if(news.getArea_county()!=null){
					sqlS.append(" AND tc.area_county="+news.getArea_county() + "");
				}else if(news.getArea_city()!=null){
					sqlS.append(" AND tc.area_city="+news.getArea_city() + "");
				}else if(news.getArea_province()!=null){
					sqlS.append(" AND tc.area_province="+news.getArea_province() + "");
				}
			}
			logger.info("findAllYpNewsEntityCount excute sql: " + sqlS.toString());
			sql= sqlS.toString();
				iCount=this.getOneInt();
			
		} catch (Exception e) {
			logger.error("findAllYpNewsEntityCount fail !!!" + e.getMessage());
			e.printStackTrace();
		} 
		return iCount;
	}
	
	/**
	 * 获得所有黄页内容信息
	 * @param hashMap
	 * @param firstrow
	 * @param maxrow
	 * @return List<NewsVo>
	 */
	public List<NewsVo> findAllYpNewsEntity(DataMap hashMap, Integer firstrow,Integer maxrow){
		JsonPage jpage=(JsonPage) hashMap.get("jpage");
		NewsVo news=(NewsVo) hashMap.get("news");
		List<NewsVo> newsList = null; 
		Object s_role_id = hashMap.get("role_id");
		Object s_user_id = hashMap.get("user_id");
		String userids = (String)hashMap.get("userids");
		try {
			
			StringBuffer sqlS =new StringBuffer("select tc.contentid,nc.cid,tc.contenttitle,tc.content_status,tc.user_id," +
			"tc.updatetime,tc.cause from t_ypcontents tc,news_contenttitle nc ");
			if(news!=null && news.getChannelId()!=null&& news.getChannelId().toString().trim().length() > 0) {
				sqlS.append(",news_extends_channel nec,news_extends_channel_title nect ");
				sqlS.append(" where nec.channel_id='"+news.getChannelId()+"' and nec.channleid=nect.channleid and nc.cid=nect.cid ");
				sqlS.append(" and nc.contentid=tc.contentid");
			}
			else
				sqlS.append(" where nc.contentid=tc.contentid ");
			if(s_role_id!=null&&!"".equals(s_role_id)) {
				sqlS.append(" and tc.user_id = '"+ s_user_id +"'");
			}else if(userids!=null){
				sqlS.append(" and tc.user_id in ("+ userids +")");
			}
			
			if(news!=null){
				if(news.getContentName()!=null&& news.getContentName().toString().trim().length() > 0){
					sqlS.append(" AND tc.contenttitle like '%" + news.getContentName().toString().trim() + "%'");
				}
				if(news.getContentStatus()!=null&& news.getContentStatus().toString().trim().length() > 0){
					sqlS.append(" AND tc.content_status='" + news.getContentStatus().toString().trim() + "'");
				}
				if(news.getArea_county()!=null){
					sqlS.append(" AND tc.area_county="+news.getArea_county() + "");
				}else if(news.getArea_city()!=null){
					sqlS.append(" AND tc.area_city="+news.getArea_city() + "");
				}else if(news.getArea_province()!=null){
					sqlS.append(" AND tc.area_province="+news.getArea_province() + "");
				}
			}
			
			if(jpage!=null){
				if(jpage.getSidx()!=null&&!"".equals(jpage.getSidx())){
					sqlS.append(" order by "+jpage.getSidx()+" "+jpage.getSord()+"");
				}
			}
			if(firstrow!=null&&maxrow!=null){
				sqlS.append(" limit "+firstrow+","+maxrow+"");
			}
			logger.info("findAllYpNewsEntity excute dql: " + sqlS.toString());
			ArrayList conList=null;
		//	ArrayList conList = this.queryALLResultSet(sqlS.toString());
			newsList=new ArrayList<NewsVo>();
			NewsVo newsVo=null;
			SimpleDateFormat fmt_temp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			if(conList.size()>0)
			{
				for(int i=0;i<conList.size();i++)
				{
					HashMap tmp = (HashMap)conList.get(i);
					newsVo=new NewsVo();
					newsVo.setContentId((String)tmp.get("contentid"));
					newsVo.setCid(Integer.parseInt((String)tmp.get("cid")));
					newsVo.setContentName((String)tmp.get("contenttitle"));
					newsVo.setContentStatus((String)tmp.get("content_status"));
					newsVo.setUserId((String)tmp.get("user_id"));
					newsVo.setLastupdatetime(fmt_temp.parse((String)tmp.get("updatetime")));
					newsVo.setCause((String)tmp.get("cause"));
					sql="select sum(nr.size) sizenr from news_contenttitle nc,news_resources nr,news_contenresource ncr"
						+" where nc.cid="+newsVo.getCid()+" and nc.cid=ncr.cid and nr.rid=ncr.rid group by ncr.cid";
					String sizestr = queryOne(sql);
					int size = 0;
					if(sizestr != null && !"".equals(sizestr))
					{
						size = Integer.parseInt(sizestr);
						newsVo.setAttachSize(size/1024+" K");
					}
					newsList.add(newsVo);
				}
			}
		
		} catch (Exception e) {
			logger.error("findAllYpNewsEntity fail !!!" + e.getMessage());
			e.printStackTrace();
		}
		return newsList;
	}
	
	public NewsVo getYpNewsByCOntentid(String contentid)
	{
		NewsVo tmp = null;
		this.sql = "SELECT n FROM TYpContents n where n.contentid=:contentid";
		try {
			Query query = em.createQuery(sql);
			query.setParameter("contentid", contentid);
			TYpContents s = (TYpContents) query.getSingleResult();
			if(s != null)
			{
				tmp = new NewsVo();
				tmp.setCid(((NewsContenttitle)s.getNewsContenttitleSet().toArray()[0]).getCid());
				tmp.setContentId(s.getContentid());
				tmp.setContentName(s.getContenttitle());
				tmp.setArea(s.getArea());
				tmp.setArea_province(s.getArea_province());
				tmp.setArea_city(s.getArea_city());
				tmp.setArea_county(s.getArea_county());
				tmp.setContentHtml(s.getHtml());
				tmp.setLastupdatetime(s.getUpdatetime());
				tmp.setUserId(s.getUserId());
				tmp.setContentStatus(s.getContentStatus());
				tmp.setCause(s.getCause());
			}
		} catch (Exception e) {
			log.error(" getYpNewsByCOntentid fail !!!" +e.getMessage());
			e.printStackTrace();
		}
		return tmp;
	}
	
	public int getResSize(String contentid)
	{
		sql = "SELECT sum(size) FROM news_resources nr,news_contenresource ncr,news_contenttitle nc " +
				"where nc.contentid='"+contentid+"' and ncr.cid=nc.cid and nr.rid=ncr.rid";
		try {
			log.info(" getResSize excute sql:" +sql);
			
				
			return this.getOneInt()/1024;
		} catch (Exception e) {
			log.info(" getResSize fail !!!" +e.getMessage());
			e.printStackTrace();
			return 0;
		}
	}
	
	public String addYpNews(NewsVo news) 
	{
		String cid=null;
		String contentid = this.ObjectToStringDB(news.getContentId());
		String contentname = this.ObjectToStringDB(news.getContentName());
		String area = this.ObjectToStringDB(news.getArea());
		String html = this.ObjectToStringDB(news.getContentHtml());
		String userid = this.ObjectToStringDB(news.getUserId());
		String constatus = this.ObjectToStringDB(news.getContentStatus());
		Integer area_province = news.getArea_province();
		Integer area_city = news.getArea_city();
		Integer area_county = news.getArea_county();
		sql = "insert into t_ypcontents (contentid,contenttitle,area,area_province,area_city,area_county,html,user_id,"+
				"content_status) values ("+contentid+","+contentname+","+area+","+area_province+","+area_city+","+area_county+","+html+","+userid+","+constatus+")";
		em.createNativeQuery(sql).executeUpdate();
		String contenticon = SysProperty.getPrep("sysiconid_title");
		if(contenticon == null || contenticon.equals(""))
        	contenticon = "1";
		NewsContenttitle contenttitle=new NewsContenttitle();
		contenttitle.setContentid(news.getContentId());
		contenttitle.setContenttitle(news.getContentName());
		contenttitle.setContenticon(Integer.valueOf(contenticon));
		contenttitle.setNewstype(news.getNewstype());
		contenttitle.setWeburl(news.getWeburl());
		em.persist(contenttitle);
		cid=contenttitle.getCid()+"";
		
		//ypnews在news_extends_channel_title表中新建状态是11  审核成功为12
		String newChSql="insert into news_extends_channel_title(channleid,cid,contentstatus,istest,isnew)VALUES(";
		String[] chIds = news.getChannelId().split(",");
		//栏目和内容的关系
		int channleid=0;
		for (int i = 0; i < chIds.length; i++) {
			sql="select channleid from news_extends_channel where channel_id="+chIds[i]+"";
			channleid=this.getOneInt();
			
			sql=newChSql+channleid+","+cid+",11,1,1)";
			em.createNativeQuery(sql).executeUpdate();
		}
		return cid;
	}

	public boolean updateYpNews(NewsVo news) {
		// 更新contenttitle，where cid=？
		// 更新t_ypcontents where contentid=?
		ArrayList<String> sqlList = new ArrayList<String>();
		String title = news.getContentName();
		String area = this.ObjectToStringDB(news.getArea());
		String html = news.getContentHtml();
		String contentid = news.getContentId();
		Integer cid = news.getCid();
		Integer area_province = news.getArea_province();
		Integer area_city = news.getArea_city();
		Integer area_county = news.getArea_county();
		String content_status = news.getContentStatus();
		String[] chIds = news.getChannelId().split(",");
		//update t_ypcontents
		sql = "update t_ypcontents set contenttitle='"+title+"',content_status='"+content_status+"',area="+area +",area_province="+area_province+",area_city="+area_city+",area_county="+area_county+",html='" +html+"' where "+
				"contentid='"+contentid+"'";
		em.createNativeQuery(sql).executeUpdate();
		//update news_contenttitle
		sql = "update news_contenttitle set contenttitle='"+title+"',updatetime=now()  where cid="+cid;
		em.createNativeQuery(sql).executeUpdate();
		//delete news_extends_channel_title
		sql = "delete from news_extends_channel_title where cid="+cid;
		em.createNativeQuery(sql).executeUpdate();
		
		String newChSql="insert into news_extends_channel_title(channleid,cid,contentstatus,istest,isnew)VALUES(";
		int channleid=0;
		for (int i = 0; i < chIds.length; i++) {
			sql="select channleid from news_extends_channel where channel_id="+chIds[i]+"";
			channleid=this.getOneInt();
			
			sql=newChSql+channleid+","+cid+",11,1,1)";
			em.createNativeQuery(sql).executeUpdate();
		}
		return true;
	}
	
	public void addYpNewsResource(NewsResources newsResources, NewsVo news) {
			sql = "insert into news_resources (name,resourcetype,url,size,rformat,spcode,newformat,fullpath) values ('"+newsResources.getName()+"',"+
			newsResources.getResourcetype()+",'"+newsResources.getUrl()+"',"+newsResources.getSize()+",'"+newsResources.getRformat()+"'," +
				"'"+newsResources.getSpcode()+"','"+newsResources.getNewformat()+"','"+newsResources.getFullpath()+"')";
    	em.createNativeQuery(sql).executeUpdate();
    		sql = "insert into news_contenresource (rid,cid) values ((select LAST_INSERT_ID()),"+news.getCid()+")";
		em.createNativeQuery(sql).executeUpdate();
		
		log.info("addHdNewsResource excute sql: "+sql);
	
	}
	
	public boolean deleteContentRrsource(String url) {
		sql = "SELECT rid FROM news_resources WHERE url='"+url+"'";
		List<Integer> lll =em.createNativeQuery(sql).getResultList();
		if(lll != null && lll.size()>0)
		{
			for(int i=0;i<lll.size();i++)
			{
				Integer rid=lll.get(i);
				this.sql = "DELETE FROM news_contenresource WHERE rid ="+rid;
				em.createNativeQuery(sql).executeUpdate();
			}
		}
		
		return true;
	}
	
//	public ArrayList findResourceByNews(Integer cid)
//	{
//		String findSql = "SELECT nr.* FROM news_resources nr,news_contenresource ncr where ncr.cid="+cid+" and ncr.rid=nr.rid ";
//		try {
//		//	return this.queryALLResultSet(findSql.toString());
//			return null;
//		} catch (Exception e) {
//			log.error(" findResourceByNews fail !!!" +e.getMessage());
//			e.printStackTrace();
//			return null;
//		}
//	}
	
	public String getExistFilename(Integer cid){
		String sql = "select nr.url from news_contenresource ncr, news_resources nr where ncr.cid ="+cid+" " +
				"and ncr.rid=nr.rid and nr.rformat in ('mp3','3gp','mp4','aac')";
		try {
			return this.queryOne(sql);
		} catch (Exception e) {
			log.error(" getExistFilename fail !!!" +e.getMessage());
			return null;
		}
	}
	
	public boolean deleteYpNews(String contentid) {
		/*Object cid = this.getSingleResult("select cid from NewsContenttitle where contentid='"+contentid+"'");
		try {
			ArrayList ridList = this.queryALLResultSet("select rid from news_contenresource where cid="+cid);
			String ridstr = "";
			for(int i=0;i<ridList.size();i++)
			{
				DataMap tmp = (DataMap)ridList.get(i);
				String one = (String)tmp.get("rid");
				ridstr+="'"+one+"',";
			}
			if(!"".equals(ridstr)){
				ridstr=ridstr.substring(0, ridstr.length()-1);
	    	}
			ArrayList<String> sqlList = new ArrayList<String>();
			String deleteSql = "delete from t_ypcontents where contentid ='"+contentid+"'";
			sqlList.add(deleteSql);
			deleteSql = "delete from news_extends_channel_title where cid ="+cid;
			sqlList.add(deleteSql);
			deleteSql = "insert into t_resourcedelete (url,format) (select nr.fullpath,nr.newformat from news_resources nr,news_contenresource ncr " +
			"where ncr.cid="+cid+" and ncr.rid=nr.rid)";
			sqlList.add(deleteSql);	
			deleteSql = "delete from news_contenresource where cid="+cid;
			sqlList.add(deleteSql);
			if(!"".equals(ridstr)){
				deleteSql = "delete from news_resources where rid in ("+ridstr+")";
				sqlList.add(deleteSql);
			}
			sqlList.add(deleteSql);
			deleteSql = "delete from news_contenttitle where contentid='"+contentid+"'";
			sqlList.add(deleteSql);
			return this.execTransaction(sqlList);
		} catch (Exception e) {
			log.info(" deleteYpNews fail !!!" +e.getMessage());
			e.printStackTrace();
			return false;
		}*/
		
		//20111010
		sql="select cid from news_contenttitle where contentid='"+contentid+"'";
		int cid=getOneInt();
		
		sql="delete from t_ypcontents where contentid ='"+contentid+"'";
		em.createNativeQuery(sql).executeUpdate();
		
		sql="delete from news_extends_channel_title where cid ="+cid;
		em.createNativeQuery(sql).executeUpdate();
		
		sql="insert into t_resourcedelete (url,format) (select nr.fullpath,nr.newformat from news_resources nr,news_contenresource ncr " +
		"where ncr.cid="+cid+" and ncr.rid=nr.rid)";
		em.createNativeQuery(sql).executeUpdate();
	
		sql="select rid from news_contenresource where cid="+cid+"";
		List<Integer> ll= em.createNativeQuery(sql).getResultList();
		
		sql="delete from news_contenresource where cid="+cid;
		em.createNativeQuery(sql).executeUpdate();
		if(ll.size()>0){
			for(int i=0;i<ll.size();i++){
				sql="delete from news_resources where rid="+ll.get(i);
				em.createNativeQuery(sql).executeUpdate();
			}
		}
		
		sql="delete from news_contenttitle where cid="+cid;
		em.createNativeQuery(sql).executeUpdate();
		
		return true;
	}
	
	public boolean subAudit(NewsVo news)
	{
		String content_id_list = news.getAllChkValue();
		String[] c_id_strList=null;
		if(content_id_list!=null && !content_id_list.equals(""))
		{
		    c_id_strList=content_id_list.split(",");
        	for(String contentId:c_id_strList)
        	{
        		 sql = "update t_ypcontents set content_status='auditing' where contentid='"+contentId+"'";
        		 em.createNativeQuery(sql).executeUpdate();
        	}
        }
		return true;
	}
	
	public boolean unpassYpNews(NewsVo news)
	{
		String content_id_list = news.getAllChkValue();
		String sql = "update t_ypcontents set content_status='unpass',cause='"+news.getCause()+"' where contentid in ("+content_id_list+")";
		try {
			log.info(" unpassYpNews excute sql :" +sql);
            return this.execUpdate(sql);
        } catch (Exception e) {
        	log.error(" unpassYpNews fail !!!" +e.getMessage());
            return false;
        }
	}
	
	public boolean udpateAuditYpNews(NewsVo news,int unpass) throws Exception{
		String content_id_list = news.getAllChkValue();
		String[] c_id_strList=null;
		if(content_id_list!=null && !content_id_list.equals(""))
		{
		    c_id_strList=content_id_list.split(",");
        	for(String contentId:c_id_strList)
        	{
        		if(unpass==1){
        			//审核不通过
        			sql = "update t_ypcontents set content_status='unpass',cause='"+news.getCause()+"' where contentid ='"+contentId+"'";
        			em.createNativeQuery(sql).executeUpdate();
        		}else{
        			sql = "update t_ypcontents set content_status='pass',cause=null where contentid='"+contentId+"'";
	        		em.createNativeQuery(sql).executeUpdate();
	        		
	        		sql = "select nr.rid,nr.spcode,nr.resourcetype,nr.url,nr.rformat,nr.fullpath from news_resources nr,news_contenresource ncr,news_contenttitle nc" +
					" where nr.resourcetype=1 and nr.rid=ncr.rid and ncr.cid=nc.cid and nc.contentid='"+contentId+"' order by rid desc";
	        		
	        		String rid = null;
	        		List<Object[]>resList =  em.createNativeQuery(sql).getResultList();
        			if(resList.size()>0)
        			{
        				String rootPath = SysProperty.getPrep("uploadpath")+"/";
        				
        				String imageSizeStr = SysProperty.getPrep("ypnews_imagesize");
        				String imageFormat = SysProperty.getPrep("hdnews_imageformat");
        				String[] imageSizeAry = null;
        				String[] imageFormatAry = null;
        				if(imageSizeStr!=null && !imageSizeStr.equals(""))
        					imageSizeAry = imageSizeStr.split(",");
        				if(imageFormat == null || imageFormat.equals(""))
        					imageFormat = "jpg";
        				if(imageFormat != null && imageFormat.contains(","))
        					imageFormatAry = imageFormat.split(",");
        				Object[] tmpMap = null; 
        				ImageScalee ims = new ImageScalee();
        				for(int i=0;i<resList.size();i++)
        				{
        					tmpMap = resList.get(i);
        					String resfilename =(String)tmpMap[5];
        					log.info(" -=-=Will be scale image file-=-= " +resfilename);
        					if(i==0)
        					{
        						rid =tmpMap[0]+"";
        						String fullpath = resfilename;
        						String imageSizeScaleStr = SysProperty.getPrep("hdnews_imagesizescale");
        			        	String imageFormatScaleStr = SysProperty.getPrep("hdnews_imageformatscale");
        			        	if(imageFormatScaleStr == null || imageFormatScaleStr.equals(""))
        			        		imageFormatScaleStr = "jpg";
        						String[] imageSizeScaleAry = imageSizeScaleStr.split(","); 
        						String[] imageFormatScaleAry = imageFormatScaleStr.split(","); 
        						if(imageSizeScaleAry != null&&imageSizeScaleAry.length>0)
        						{
        							for(String imageSizeScale:imageSizeScaleAry)
        							{
        								String screenWidHei = imageSizeScale.split("@")[0];
        								String picWidHei = imageSizeScale.split("@")[1];
        								int screenWidth = Integer.parseInt(screenWidHei.split("x")[0]);
        								int screenHeight = Integer.parseInt(screenWidHei.split("x")[1]);
        								int width = Integer.parseInt(picWidHei.split("x")[0]);
        								int height = Integer.parseInt(picWidHei.split("x")[1]);
        								if(imageFormatScaleAry!=null && imageFormatScaleAry.length>0)
        									for(String imageFormatScale:imageFormatScaleAry)
        										ims.compressPicsScaleHd(fullpath, width, height, imageFormatScale, screenWidth, screenHeight);
        							}
        						}
        						String scaleFullPath = fullpath.replace(".", "-p.");
        						sql = "insert into news_resources (name,newformat,fullpath) values('"+rid+"','"+imageFormatScaleStr+"','"+scaleFullPath+"')";
        						em.createNativeQuery(sql).executeUpdate();
        					}
//			        					String resfilename = fullpath;//rootPath+tmpMap.get("spcode")+"/"+tmpMap.get("resourcetype")+"/"+tmpMap.get("url")+"."+tmpMap.get("rformat");
        					if(!"".equals(resfilename) && imageSizeAry != null)
        					{
        						for(String imageSize : imageSizeAry)
        						{
        							String screenWidHei = imageSize.split("@")[0];
        							String picWidHei = imageSize.split("@")[1];
        							int screenWidth = Integer.parseInt(screenWidHei.split("x")[0]);
        							int screenHeight = Integer.parseInt(screenWidHei.split("x")[1]);
        							int width = Integer.parseInt(picWidHei.split("x")[0]);
        							int height = Integer.parseInt(picWidHei.split("x")[1]);
        							if(imageFormatAry != null)
        								for(String imageFormatStr : imageFormatAry)
        									ims.compressPicsHd(resfilename, width, height, imageFormatStr,screenWidth,screenHeight);
        							else
        								ims.compressPicsHd(resfilename, width, height, imageFormat,screenWidth,screenHeight);
        						}
        					}
        				}
        			}
	        		
        			if(rid!=null){
        				sql="select n.rid from news_resources n where n.name='"+rid+"'";
						int iconrid = getOneInt();
						if(iconrid>0){
							sql = "update news_contenttitle set contenticon="+iconrid+" where contentid='"+contentId+"'";
		                	em.createNativeQuery(sql).executeUpdate();
						}
			        }else{
			        	String contenticon = SysProperty.getPrep("sysiconid_title");
	        			if(contenticon == null || contenticon.equals(""))
	        	        	contenticon = "1";
	        			sql = "update news_contenttitle set contenticon='"+contenticon+"' where contentid='"+contentId+"'";
	                	em.createNativeQuery(sql).executeUpdate();
			        }
	        		
	    			//修改内容在栏目表的状态,硬件资讯9为通过审核
	        		sql="select cid from news_contenttitle where contentid='"+contentId+"'";
    				int cid = getOneInt();
	    			sql = "update news_extends_channel_title set contentstatus=12 where cid=" + cid;
	    			em.createNativeQuery(sql).executeUpdate();
    				//todo执行生成静态网页
    				NewsVo newsvo = this.getYpNewsByCOntentid(contentId);
    				Executor executor = Executors.newSingleThreadExecutor();
    				Map<String, String> m=getUrl_NewformatByContentid(contentId);
    				executor.execute(new GenerateNewsHtml(newsvo,YPNEWS_TYPE,m));
        		}
        		
        	}
	    }
		
		return true;
	}

	public boolean disableYpNews(String contentIdStr)
	{
		ArrayList<String> sqlList = new ArrayList<String>();
		sql = "update t_ypcontents set content_status='disable' where contentid in ("+contentIdStr+")";
		sqlList.add(sql);
		String cidstr = this.getCidListByContentid(contentIdStr);
		sql = "update news_extends_channel_title set contentstatus=13 where cid in (" + cidstr +")";
		sqlList.add(sql);
		try {
			return execTransaction(sqlList);
		} catch (Exception e) {
			log.error(" disableYpNews fail !!!" +e.getMessage());
			e.printStackTrace();
			return false;
		}
	}
	
	public String getCidListByContentid(String contentIdStr)
	{
		sql= "SELECT cid FROM news_contenttitle where contentid in ("+contentIdStr+")";
		String result = "";
		try {
			List<Object[]> tempp=this.em.createNativeQuery(sql).getResultList();
			for(Object[]o:tempp)
			{
				String cid = this.getString(o[0]);
				result += cid+",";
			}
			if(!"".equals(result))
				result = result.substring(0,result.length()-1);
		} catch (Exception e) {
			logger.error(" getCidListByContentid fail !!!" +e.getMessage());
		}
		return result;
	}
	
	public ArrayList<DataMap> findSelectChannelsByCid(Integer cid)
	{
		sql = "select   ch.channel_id  ,ch.service_code,ch.channel_name,ch.channel_comment ,ch.function_name,ch.STATUS ,ch.ordered ,ch.created_date" +
		",ch.previous_id ,ch.primal_id ,ch.LEVEL ,ch.channel_type  ,ch.channel_hot_topics ,ch.channel_classifying_label" +" from t_channels tc,news_extends_channel nec,news_extends_channel_title nect " +
				"where nect.cid="+cid+" and nect.channleid=nec.channleid and nec.channel_id=tc.channel_id";
		try {
			return null;
			//return this.queryALLResultSet(findSql.toString());
		} catch (Exception e) {
			logger.error(" findAllLastChannel fail !!!" +e.getMessage());
			return null;
		}
	}

	public ArrayList<DataMap> findAllLastChannel(DataMap hashMap) {
		Object roleId = hashMap.get("role_id");
		Object userId = hashMap.get("user_id");
		String userids = (String)hashMap.get("userids");
		//root
		String findSql = "select  ch.channel_id  ,ch.service_code,ch.channel_name,ch.channel_comment ,ch.function_name,ch.STATUS ,ch.ordered ,ch.created_date" +
				",ch.previous_id ,ch.primal_id ,ch.LEVEL ,ch.channel_type  ,ch.channel_hot_topics ,ch.channel_classifying_label" +" from t_channels ch WHERE 1=1 " +
				//will open
				" and channel_type='"+BookConfig.channel_type_yellowpage+"' " + 
				" AND (function_name='"+BookConfig.channel_last+"' OR function_name='"+BookConfig.channel_song+"') ";
		//normal user
		if(roleId != null && !roleId.equals(""))
		{
			findSql = "select  ch.channel_id  ,ch.service_code,ch.channel_name,ch.channel_comment ,ch.function_name,ch.STATUS ,ch.ordered ,ch.created_date" +
				",ch.previous_id ,ch.primal_id ,ch.LEVEL ,ch.channel_type  ,ch.channel_hot_topics ,ch.channel_classifying_label" +" from t_channels ch,t_user_channels uc WHERE ch.channel_id=uc.channel_id " +
					" and channel_type='"+BookConfig.channel_type_yellowpage+"' " + 
		    		" and (function_name='"+BookConfig.channel_last+"' OR function_name='"+BookConfig.channel_song+"')  " +
		    		" and uc.employee_id=(SELECT employee_id FROM t_user where user_id='" + userId + "')";
		}else if(userids!=null){
			findSql = "select distinct  ch.channel_id  ,ch.service_code,ch.channel_name,ch.channel_comment ,ch.function_name,ch.STATUS ,ch.ordered ,ch.created_date" +
				",ch.previous_id ,ch.primal_id ,ch.LEVEL ,ch.channel_type  ,ch.channel_hot_topics ,ch.channel_classifying_label" +" from t_channels ch,t_user_channels uc WHERE ch.channel_id=uc.channel_id " +
			" and channel_type='"+BookConfig.channel_type_yellowpage+"' " + 
    		" and (function_name='"+BookConfig.channel_last+"' OR function_name='"+BookConfig.channel_song+"')  " +
    		" and uc.employee_id in (SELECT employee_id FROM t_user where user_id in (" + userids + "))";
		}
		findSql+=" order by previous_id";
		try {
			return null;
			//return this.queryALLResultSet(findSql.toString());
		} catch (Exception e) {
			logger.error(" findAllLastChannel fail !!!" +e.getMessage());
			return null;
		}
	}
	
	public ArrayList<DataMap> getAllAreaOne() {
		try {
			return null;
			//return this.queryALLResultSet("SELECT * FROM t_areainfo WHERE arealevel=1  ");
		} catch (Exception e) {
			logger.error(" getAllAreaOne fail !!!" +e.getMessage());
			return null;
		}
	}
	
	/*public ArrayList<DataMap> findAllLastChannel(Object roleId, String userId) {
		//root
		String findSql = "select ch.* from t_channels ch WHERE 1=1 " +
				//will open
				" and status='"+BookConfig.channel_status_enable+"'" +
				" and channel_type='"+BookConfig.channel_type_yellowpage+"' " + 
				" AND (function_name='"+BookConfig.channel_last+"' OR function_name='"+BookConfig.channel_song+"') ";
		//normal user
		if(roleId != null && !roleId.equals(""))
		{
			findSql = "select ch.* from t_channels ch,t_user_channels uc WHERE ch.channel_id=uc.channel_id " +
		    		" and status='"+BookConfig.channel_status_enable+"'" +
					" and channel_type='"+BookConfig.channel_type_yellowpage+"' " + 
		    		" and (function_name='"+BookConfig.channel_last+"' OR function_name='"+BookConfig.channel_song+"')  " +
		    		" and uc.employee_id=(SELECT employee_id FROM t_user where user_id='" + userId + "')";
		}
		try {
			return this.queryALLResultSet(findSql.toString());
		} catch (Exception e) {
			logger.error(" findAllLastChannel fail !!!" +e.getMessage());
			return null;
		}
	}*/
	
	public String getAreaNameById(Integer areaid)
	{
		 sql = "SELECT areaname FROM t_areainfo WHERE areaid="+areaid;
		String areaname="";
		try {
			return this.getOneString();
		} catch (Exception e) {
			logger.error(" getAreaNameById fail !!!" +e.getMessage());
			return null;
		}
	}
	
	/*public String getFullAreaNameById(String fullname,String areaid)
	{
		String sql = "SELECT * FROM t_areainfo WHERE areaid="+areaid;
		
		try {
			DataMap result = this.queryOneRow(sql);
			fullname = result.getMapData("areaname")  + "-" + fullname;
			if(result != null && !result.isEmpty() && !result.getMapData("upareaid").equals("0"))
			{
				fullname = getFullAreaNameById(fullname,result.getMapData("upareaid"));
			}
			return fullname;
		} catch (Exception e) {
			logger.error(" getAreaNameById fail !!!" +e.getMessage());
			return null;
		}
	}*/
	
	public DataMap buildLastChannelMap()
    {
    	String sql = "SELECT channel_id,channel_name,function_name,previous_id FROM t_channels t";
    	HashMap<String,String> childIdAndPreiousId = new HashMap<String,String>();
    	HashMap<String,String> idAndName = new HashMap<String,String>();
    	DataMap result = new DataMap();
    	List chList = null;
    	try {
		//	chList = queryALLResultSet(sql);
		} catch (Exception e) {
			log.info(" NewsServiceImpl3 buildChChildIdAndPreviousIdMap fail !!!" +e.getMessage());
			e.printStackTrace();
			return null;
		}
		//首先建立两个map准备数据
		for(int i=0;i<chList.size();i++)
		{
			HashMap hashMap = (HashMap)chList.get(i);
			String channel_id = (String)hashMap.get("channel_id");
			String chName = (String)hashMap.get("channel_name");
			String fnName = (String)hashMap.get("function_name");
			String previous_id = (String)hashMap.get("previous_id");
			//先将id和name装入map
			idAndName.put(channel_id, chName);
			//channel如果是normal或者first,就装入map,key是channel_id,value是
			if(fnName.equals(BookConfig.channel_first) || fnName.equals(BookConfig.channel_normal))
			{
				childIdAndPreiousId.put(channel_id, previous_id);
			}
		}
		//build map,key:channleid value:previousid+name
		for(int i=0;i<chList.size();i++)
		{
			HashMap hashMap = (HashMap)chList.get(i);
			String channel_id = (String)hashMap.get("channel_id");
			String chName = (String)hashMap.get("channel_name");
			String fnName = (String)hashMap.get("function_name");
			String previous_id = (String)hashMap.get("previous_id");
			//如果是normal或者first,就装入map,key是channel_id,value是
			if(fnName.equals(BookConfig.channel_last) || fnName.equals(BookConfig.channel_song))
			{
				String previousChName = idAndName.get(previous_id);
				chName = chName+"="+previousChName;
				chName = getValue(childIdAndPreiousId,idAndName,previous_id,chName);
				//最上一级的频道名称必然是news,把news过滤掉
				chName = chName.substring(0,chName.lastIndexOf("="));
				String[] tmp = chName.split("=");
				String value = "";
				for(int j=tmp.length-1;j>=0;j--)
				{
					value=value+tmp[j]+"--";
				}
				value = value.substring(0,value.length()-2);
				result.put(channel_id, value);
			}
		}
    	return result;
    }
	
	private String getValue(HashMap<String,String> idmap,HashMap<String,String> namemap,String key,String result)
    {
    	String parentid = idmap.get(key);
    	String parentname = namemap.get(parentid);
    	if((key != null && parentid!=null)&& !parentid.equals(key))
    	{
    		result = result+"="+parentname;
    		return getValue(idmap,namemap,parentid,result);
    	}
    	else
    	{
    		return result;
    	}
    }
	
//	private String ObjectToStringDB(Object obj) {
//        try {
//            String str = obj.toString().trim();
//
//            if (str.equals("") || str.equals("null")) {
//                return "null";
//            }
//
//            return "'" + str + "'";
//        } catch (Exception e) {
//            return "null";
//        }
//    }

	public List<TAreainfo> findAllAreainfo(int upareaid) {
		List<TAreainfo> queryList=new ArrayList<TAreainfo>();
    	try {
	    	StringBuffer sqlS = new StringBuffer("SELECT p FROM TAreainfo p WHERE p.upareaid=:upareaid and p.areaid!=0");
	    	sqlS.append(" order by p.areaid");
	        Query query = em.createQuery(sqlS.toString());      
	        query.setParameter("upareaid", upareaid);
	        queryList=query.getResultList();  
    	} catch (Exception e) {
			e.printStackTrace();
		}
        return queryList;
	}
	
	
	public boolean updateNewsContenttitle_htmlToUrl(NewsVo news) {
		try {
			sql="update news_contenttitle set contenthtml='"+news.getContentHtml()+"',weburl='"+news.getWeburl()+"' where cid='"+news.getCid()+"'";
			em.createNativeQuery(sql).executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}
	
	//得到内容的url-newformatMap映射，处理base64图片时候用
	public Map<String, String> getUrl_NewformatByContentid(String contentId) {
		 sql="select nr.url,nr.newformat from news_resources nr,news_contenresource ncr,news_contenttitle nc where nr.rid=ncr.rid and ncr.cid=nc.cid and nc.contentid=:contentId";
		 Map<String, String> m=new HashMap<String, String>();
		 List<Object[]> ll=em.createNativeQuery(sql).setParameter("contentId", contentId).getResultList();
		 if(ll.size()>0){
			 for(int i=0;i<ll.size();i++){
				 m.put((String)ll.get(i)[0], (String)ll.get(i)[1]);
			 }
		 }
    	 return m;                                      
	}
	
	
	//not use
//	public ArrayList getChannelPlatform()
//    {
//    	ArrayList result = new ArrayList();
//    	//1 取得所有生效的catalog对应的catalogchannelid
//    	String sql = "SELECT ncc.channelid,ncp.* FROM news_catlog nc left join news_catlog_platform ncp on ncp.catlogid=nc.catlogid," +
//    			"news_catlog_channel ncc where nc.isnowpublish in (1,2) and nc.catlogid=ncc.catlogid";
//    	ArrayList catalogChannelidAndPlatformList = new ArrayList();
//    	try {
//    		catalogChannelidAndPlatformList = queryALLResultSet(sql);
//    		if(catalogChannelidAndPlatformList.size()>0)
//    		{
//	    		for(int i=0;i<catalogChannelidAndPlatformList.size();i++)
//	    		{
//	    			DataMap lastChannelAndPlatform = new DataMap();
//	    			HashMap hashmap = (HashMap)catalogChannelidAndPlatformList.get(i);
//	    			String catalogChannelid = (String)hashmap.get("channelid");
//	    			String platforminfo = InterUtil.rb.getString("src.gameplatform")+hashmap.get("mplatform")+"."+
//	    			InterUtil.rb.getString("src.gamedistributor")+hashmap.get("magent")+"."+InterUtil.rb.getString("src.clientsn")+
//	    			hashmap.get("mserialnum")+"."+InterUtil.rb.getString("src.languagearea")+hashmap.get("mlocale");
//	    			sql = "SELECT nc.channel_id FROM news_buttons nb,news_extends_firstchannel_buttons nfb,news_contenttype nc where " +
//	    					"nfb.channelid="+catalogChannelid+" and nc.newscontenttype=nb.buttoncontenttype and nfb.buttonid=nb.buttonid";
//	    			ArrayList tchannelIdList = queryALLResultSet(sql);
//	    			if(tchannelIdList.size()>0)
//	    			{
//	    				//首先要判断结果集里的channel是否最后一级
//	    				for(int j=0;j<tchannelIdList.size();j++)
//	    				{
//	    					DataMap tmpMap = (DataMap)tchannelIdList.get(j);
//	    					String tch_id = tmpMap.getMapData("channel_id");
//	    					if(tch_id == null || tch_id.equals(""))
//	    						continue;
//	    					sql = "select function_name from t_channels where channel_id='"+tch_id+"'";
//	    					String functionname = queryOne(sql);
//	    					//if最后一级 放到map里 key是最后一级的id value是platforminfo
//	    					if(functionname.toUpperCase().equals("LAST") || functionname.toUpperCase().equals("CHANNELSONG"))
//	    						lastChannelAndPlatform.put(tch_id, platforminfo);
//	    					//不是 递归查询
//	    					else
//	    						buildLastChannelAndPlatform(tch_id,platforminfo,lastChannelAndPlatform);
//	    				}
//	    			}
//	    			result.add(lastChannelAndPlatform);
//	    		}
//    		}
//		} catch (Exception e) {
//			log.info(" NewsServiceImpl3 getChannelPlatform fail !!!" +e.getMessage());
//			e.printStackTrace();
//		}
//    	return result;
//    }
//	//not use
//	private void buildLastChannelAndPlatform(String tch_id,String platforminfo,DataMap lastChannelAndPlatform)
//    {
//    	String sql = "SELECT channel_id,function_name FROM t_channels where previous_id='"+tch_id+"'";
//    	try {
//			ArrayList chList = queryALLResultSet(sql);
//			for(int i=0;i<chList.size();i++)
//			{
//				HashMap hashMap = (HashMap)chList.get(i);
//				String fnName = (String)hashMap.get("function_name");
//				String channel_id = (String)hashMap.get("channel_id");
//				if(fnName.toUpperCase().equals("LAST") || fnName.toUpperCase().equals("CHANNELSONG"))
//					lastChannelAndPlatform.put(channel_id, platforminfo);
//				else
//					buildLastChannelAndPlatform(channel_id,platforminfo,lastChannelAndPlatform);
//			}
//		} catch (Exception e) {
//			log.info(" NewsServiceImpl3 buildLastChannelAndPlatform fail !!!" +e.getMessage());
//			e.printStackTrace();
//		}
//    }
}
